//
//  CoreDataManager.m
//  BasketballClub
//
//  Created by dhz on 16/1/19.
//  Copyright © 2016年 孙鸿吉. All rights reserved.
//

#import "CoreDataManager.h"
#import "NewsModel.h"
#import "VideoModel.h"
#import "SkillModel.h"
#import "NBAorCBA.h"
#import "Skill.h"
#import "CBA.h"
#import "Person.h"
#import "Video.h"
#import "OwnerView.h"
#import "OnlyOne.h"
#import "LoginView.h"
#import "Today.h"
#import "Yesterday.h"
#import "Tomorrow.h"
#import "LiveModel.h"
static CoreDataManager *manager = nil;
@implementation CoreDataManager

+(instancetype)shareCoreDateManager
{
    return [[self alloc ]init];
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [super allocWithZone:zone];
        }
    });
    return manager;
}


-(void)create
{
    //创建模型对象
    NSManagedObjectModel *managerModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    //创建连接的桥梁
    self.storeCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:managerModel];
    
    //确定存储位置
  NSString *  path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    //拼接最终的路径
    path = [path stringByAppendingPathComponent:@"LcacheData"];
    //连接路径
    NSError *error =  nil;
    
    
    NSDictionary  *dictionary = @{NSMigratePersistentStoresAutomaticallyOption:[NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption:[NSNumber numberWithBool:YES]};
    
    //连接
    [self.storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:dictionary error:&error];
    
    //初始化管理上下文
    self.context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    //连接器
    self.context.persistentStoreCoordinator  = self.storeCoordinator;

}






-(void)insertOwnerDataToSql:(OwnerView *)view with:(LoginView *)login
{
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    
    OnlyOne *only = [NSEntityDescription insertNewObjectForEntityForName:@"OnlyOne" inManagedObjectContext:self.context];
    only.usernameTF = login.usernameTF.text;
    person.userNickName =view.userNickName.text;
    person.userStyle = view.userStyle.text;
    NSData *imageData = UIImagePNGRepresentation(view.backGroundImageView.image);
    person.backGroundImageView = imageData;
    person.onlyOne.usernameTF = login.usernameTF.text;
    person.headImageView = UIImagePNGRepresentation(view.headImageView.image);
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }
    
    
}



#pragma mark --- 插入Video到数据库中
-(void)insertVideoDataToSql:(VideoModel*)model
{
    
    Video *video = [NSEntityDescription insertNewObjectForEntityForName:@"Video" inManagedObjectContext:self.context];
    video.title = model.title;
    video.duration = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.duration] integerValue]];
    video.imglink = model.imglink;
    video.iD = [NSNumber numberWithInteger:model.iD];
    video.url = model.url;
    video.readarts = [NSString stringWithFormat:@"%@",model.readarts];
    video.videolink = model.videolink;
    
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }

    
    
}
#pragma mark --- 插入News数据到数据库中
-(void)insertNBANewsDataToSql:(NewsModel*)model
{
    
    NBAorCBA *ncba = [NSEntityDescription insertNewObjectForEntityForName:@"NBAorCBA" inManagedObjectContext:self.context];
    ncba.title = model.title;
    
    ncba.timeSecond =[NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.timeSecond] integerValue]];
    ncba.iD  = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.iD] integerValue]];
    ncba.readarts = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.readarts] integerValue]];
    ncba.likecount = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.likecount] integerValue]];
    ncba.content168 = model.content168;
    ncba.url = model.url;
    ncba.author = model.author;
    ncba.imglink = model.imglink;

    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }

    
    
}
-(void)insertCBANewsDataToSql:(NewsModel*)model
{
    CBA *cba = [NSEntityDescription insertNewObjectForEntityForName:@"CBA" inManagedObjectContext:self.context];
    cba.title = model.title;
    
    cba.timeSecond =[NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.timeSecond] integerValue]];
    cba.iD  = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.iD] integerValue]];
    cba.readarts = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.readarts] integerValue]];
    cba.likecount = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.likecount] integerValue]];
    cba.content168 = model.content168;
    cba.url = model.url;
    cba.author = model.author;
    cba.imglink = model.imglink;
    
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }

}



#pragma mark --- 插入Skill数据到数据库中
-(void)insertSkillDataToSql:(SkillModel*)model
{
    Skill *skill = [NSEntityDescription insertNewObjectForEntityForName:@"Skill" inManagedObjectContext:self.context];
    skill.title = model.title;
    skill.iD  = [NSNumber numberWithInteger:model.iD];
   
    skill.time = [NSNumber numberWithInteger:[[NSString stringWithFormat:@"%@",model.time] integerValue]];
    skill.readarts = [NSString stringWithFormat:@"%@",model.readarts];
    skill.imageArray = model.imageArray;
    skill.talkcount = [NSNumber numberWithInteger:model.talkcount];
    skill.likecount = [NSNumber numberWithInteger:model.likecount];
    skill.sharearts = [ NSNumber numberWithInteger:model.sharearts];
    skill.url = model.url;
    skill.readCount = [NSNumber numberWithInteger:model.readCount];
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }
   
}

-(void)insertTodayDataToSql:(LiveModel*)model
{
    Today *today = [NSEntityDescription insertNewObjectForEntityForName:@"Today" inManagedObjectContext:self.context];
    today.m_link1url = model.m_link1url;
    today.link1text = model.link1text;
    today.link1url = model.link1url;
    today.link2text = model.link2text;
    today.link2url  = model.link2url;
    today.player1 = model.player1;
    today.player1logo = model.player1logo;
    today.player2 = model.player2;
    today.player2logo = model.player2logo;
    today.score = model.score;
    today.status = [NSNumber numberWithInteger:model.status];
    today.time = model.time;
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }
    
    
}

-(void)insertYesterdayDataToSql:(LiveModel*)model
{
    Yesterday *yesterday = [NSEntityDescription insertNewObjectForEntityForName:@"Yesterday" inManagedObjectContext:self.context];
    yesterday.m_link1url = model.m_link1url;
    yesterday.link1text = model.link1text;
    yesterday.link1url = model.link1url;
    yesterday.link2text = model.link2text;
    yesterday.link2url  = model.link2url;
    yesterday.player1 = model.player1;
    yesterday.player1logo = model.player1logo;
    yesterday.player2 = model.player2;
    yesterday.player2logo = model.player2logo;
    yesterday.score = model.score;
    yesterday.status = [NSNumber numberWithInteger:model.status];
    yesterday.time = model.time;
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }

}

-(void)insertTomorrowDataToSql:(LiveModel*)model
{
    Tomorrow *tomorrow = [NSEntityDescription insertNewObjectForEntityForName:@"Tomorrow" inManagedObjectContext:self.context];
    tomorrow.m_link1url = model.m_link1url;
    tomorrow.link1text = model.link1text;
    tomorrow.link1url = model.link1url;
    tomorrow.link2text = model.link2text;
    tomorrow.link2url  = model.link2url;
    tomorrow.player1 = model.player1;
    tomorrow.player1logo = model.player1logo;
    tomorrow.player2 = model.player2;
    tomorrow.player2logo = model.player2logo;
    tomorrow.score = model.score;
    tomorrow.status = [NSNumber numberWithInteger:model.status];
    tomorrow.time = model.time;
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }

}







#pragma mark - 数据的查找

-(NSArray*)selectAllNewsNBAModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"NBAorCBA"];
    NSArray *array = [self.context executeFetchRequest:request error:nil];

       return array;
}
-(NSArray*)selectAllNewsCBAModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"CBA"];
    NSArray *array = [self.context executeFetchRequest:request error:nil];


    return  array;
}


-(NSArray*)selectAllSkillModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Skill"];
    
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    
    return  array;
}

-(NSArray*)selectAllVideoModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Video"];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
      return  array;

}

-(NSArray *)selectAllYesterdayModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Yesterday"];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    return  array;
}
-(NSArray *)selectAllTodayModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Today"];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    return  array;
}
-(NSArray *)selectAllTomorrowModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Tomorrow"];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    return  array;
}






#pragma mark -  数据的删除
-(void)deleteFromNewsModelWithID:(NSString*)ID
{
    NSInteger count  = [ID integerValue];
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"NBAorCBA"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iD=%ld",count];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    for (NBAorCBA *ncba in array) {
        [self.context deleteObject:ncba];
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }
    
}

-(void)deleteFromSkillModelWithID:(NSInteger)ID
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Skill"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iD=%ld",ID];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    for (Skill *ski in array) {
        [self.context deleteObject:ski];
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }

}

-(void)deleteFromVideoModelWithID:(NSInteger)ID;
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Video"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iD=%ld",ID];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    for (Video *vid in array) {
        [self.context deleteObject:vid];
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }

}

-(void)deleteNBANewsAllData
{
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"NBAorCBA" inManagedObjectContext:self.context];
    
    
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    [request setIncludesPropertyValues:NO];
    [request setEntity:entity];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (NBAorCBA *ncba in array) {
            [self.context deleteObject:ncba];
        }
        if (![self.context save:nil]) {
            
        }
    }
   
}
-(void)deleteCBANewsAllData
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"CBA"];
    [request setIncludesPropertyValues:NO];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (CBA *cba in array) {
            [self.context deleteObject:cba];
        }
        if ([self.context hasChanges]) {
            [self.context save:nil];
        }else{
            
        }
    }
    
}


-(void)deleteSkillAllData
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Skill"];
    [request setIncludesPropertyValues:NO];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (Skill *skill in array) {
            [self.context deleteObject:skill];
        }
        if ([self.context hasChanges]) {
            [self.context save:nil];
        }else{
            
        }
    }

}
-(void)deleteVideoAllData
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Video"];
    [request setIncludesPropertyValues:NO];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (Video *video in array) {
            [self.context deleteObject:video];
        }
        if ([self.context hasChanges]) {
            [self.context save:nil];
        }else{
    
        }
    }

}



-(void)deleteYesterdayAllData
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Yesterday"];
    [request setIncludesPropertyValues:NO];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (Yesterday *yesterday in array) {
            [self.context deleteObject:yesterday];
        }
        if ([self.context hasChanges]) {
            [self.context save:nil];
        }else{
            
        }
    }

}
-(void)deleteTomorrowAllData
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Tomorrow"];
    [request setIncludesPropertyValues:NO];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (Tomorrow *tomorrow in array) {
            [self.context deleteObject:tomorrow];
        }
        if ([self.context hasChanges]) {
            [self.context save:nil];
        }else{
            
        }
    }
}
-(void)deleteTodayAllData
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Today"];
    [request setIncludesPropertyValues:NO];
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    if (array && [array count] ) {
        for (Today *today in array) {
            [self.context deleteObject:today];
        }
        if ([self.context hasChanges]) {
            [self.context save:nil];
        }else{
            
        }
    }

}



#pragma mark - 数据的修改

#pragma mark - 数据的更改

-(void)updateOwnerBackGroundImage:(UIImageView*)imageView withUserName:(NSString *)userName
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"usernameTF=%@",userName];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    NSData *data  = UIImagePNGRepresentation(imageView.image);
    for (Person *p in array) {
        p.backGroundImageView = data;
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }
    
}
-(void)updateOwnerHeadImage:(UIImageView*)imageView withUserName:(NSString *)userName
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"usernameTF=%@",userName];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    NSData *data  = UIImagePNGRepresentation(imageView.image);
    for (Person *p in array) {
        p.headImageView = data;
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }

}
-(void)updateOwnerUserStyle:(NSString*)userStyle withUserName:(NSString *)userName
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"usernameTF=%@",userName];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];

    for (Person *p in array) {
        p.userStyle = userStyle;
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }

}
-(void)updateOwnerNickName:(NSString*)nickName withUserName:(NSString *)userName
{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"usernameTF=%@",userName];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    
    for (Person *p in array) {
        p.userNickName = nickName;
    }
    if ([self.context hasChanges]) {
        [self.context save:nil];
    }else{
        
    }
}





@end
